from flask_restplus import Resource, Namespace, fields, marshal, reqparse, Model
from common.decorators import catch_error
from app.user import service
from app.user.decorators import token_required
from common.responses import ok
from app.user.model import User, Role
from flask import g
from common import constant
from common import errors
from app.user import dao
from common.request_parser import get_parser as base_get_parser
from common.response_model import base_model, pagination_model
from app.user.role_service import PERMISSION_INFO

api = Namespace('role', path='/role')
# ---------- model start -----------
role_model = base_model.inherit('role_model', {
    'permissions': fields.List(fields.String()),
    'company_id': fields.String()
})

role_paginate_model = pagination_model.inherit('role_paginate_model', {
    "items": fields.Nested(role_model)
})

# ---------- model end -----------


create_parser = reqparse.RequestParser()
create_parser.add_argument('name', type=str, required=True)
create_parser.add_argument('notes', type=str)
create_parser.add_argument('permissions', type=str, action='append', default=[])


class RolesResource(Resource):
    @catch_error
    @token_required
    @api.expect(create_parser)
    def post(self):
        args = create_parser.parse_args()
        new_obj = Role.create(**args, commit=True)
        return ok(data=marshal(new_obj, role_model),
                  message='create success')

    @catch_error
    @token_required
    def get(self):
        """获取所有角色 (公用角色 + 私有角色)"""
        basic_roles = Role.query.filter_by(company_id=None).all()
        roles = Role.query.filter_by(company_id=g.company_id).all()
        return ok(data=marshal(basic_roles + roles, role_model), message='get successfully')
        # role_paginate = {
        #     "pages": 1,
        #     "page": 1,
        #     "per_page": 0,
        #     "total": len(basic_roles+roles),
        #     'items': basic_roles+roles
        # }
        # return ok(data=marshal(role_paginate, role_paginate_model), message='get successfully')


put_parser = create_parser.copy()


class RoleResource(Resource):
    @catch_error
    @token_required
    @api.expect(put_parser)
    def put(self, obj_id):
        args = put_parser.parse_args()
        for key in list(args.keys()):
            if args.get(key) is None:
                del args[key]

        obj = Role.query.filter_by(id=obj_id).first()
        obj.update(**args, commit=True)
        return ok(data=marshal(obj, role_model),
                  message='update success')

    @catch_error
    @token_required
    def delete(self, obj_id):
        obj = Role.query.filter_by(id=obj_id).first()
        delete_id = obj.hard_delete(commit=True)
        return ok(
            data={'id': delete_id},
            message='delete success')


class PermissionsResource(Resource):
    @catch_error
    @token_required
    def get(self):
        """获取全部权限列表"""
        # 转换成数组
        # permission_array = [[
        #     {key: }
        # ], []]
        return ok(data=PERMISSION_INFO, message='get permissions success')


# ---------- 把路由集中在这里，方便查看 -----------
api.add_resource(RolesResource, '/roles')
api.add_resource(RoleResource, '/roles/<int:obj_id>')
api.add_resource(PermissionsResource, '/permissions')
